package com.kcyu.sfhinvoice.utils;

import com.baidu.aip.contentcensor.EImgType;
import com.baidu.aip.ocr.AipOcr;
import com.kcyu.sfhinvoice.domain.InvoiceStruct;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class BaiduOcrUtils {

    public static final String APP_ID = "53745153";
    public static final String API_KEY = "rDNwzS5LjyqKV7vxkneEz75a";
    public static final String SECRET = "CNbHKNV1z4FgdBTZKDbmbSJvFtQqvgZM";

    public enum FileType {
        PDF,
        PIC
    }

    public static void main(String[] args) {
        AipOcr aipOcr = new AipOcr(APP_ID, API_KEY, SECRET);
        JSONObject jsonObject = aipOcr.vatInvoice("D:\\lls\\yujiancong\\Desktop\\测试证件\\发票\\发票1.pdf", EImgType.PDF, null);
        System.out.println(jsonObject.toString(2));
    }

    public InvoiceStruct ocrInvoice(String pdfPath, FileType fileType) throws ParseException {
        AipOcr aipOcr = new AipOcr(APP_ID, API_KEY, SECRET);
        JSONObject jsonObject = null;
        if(fileType.equals(FileType.PDF)){
            jsonObject = aipOcr.vatInvoice(pdfPath, EImgType.PDF, null);
        }
        if(fileType.equals(FileType.PIC)){
            jsonObject = aipOcr.vatInvoice(pdfPath, EImgType.FILE, null);
        }
        JSONObject wordsResult = jsonObject.getJSONObject("words_result");
        InvoiceStruct invoiceStruct = new InvoiceStruct();
        invoiceStruct.setInvoiceCode(wordsResult.getString("InvoiceCode"));
        invoiceStruct.setCheckCode(wordsResult.getString("CheckCode"));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
        invoiceStruct.setInvoiceDate(sdf.parse(wordsResult.getString("InvoiceDate")));
        invoiceStruct.setPurchaserRegisterNum(wordsResult.getString("PurchaserRegisterNum"));
        invoiceStruct.setInvoiceTypeOrg(wordsResult.getString("InvoiceTypeOrg"));
        invoiceStruct.setAmountInFiguers(new BigDecimal(wordsResult.getString("AmountInFiguers")));
        invoiceStruct.setChecker(wordsResult.getString("Checker"));
        invoiceStruct.setTotalAmount(new BigDecimal(wordsResult.getString("TotalAmount")));
        invoiceStruct.setTotalTax(new BigDecimal(wordsResult.getString("TotalTax")));
        invoiceStruct.setCity(wordsResult.getString("City"));
        invoiceStruct.setProvince(wordsResult.getString("Province"));
        invoiceStruct.setPurchaserName(wordsResult.getString("PurchaserName"));
        invoiceStruct.setInvoiceType(wordsResult.getString("InvoiceType"));
        invoiceStruct.setNoteDrawer(wordsResult.getString("NoteDrawer"));
        invoiceStruct.setSellerAddress(wordsResult.getString("SellerAddress"));
        invoiceStruct.setSellerRegisterNum(wordsResult.getString("SellerRegisterNum"));
        invoiceStruct.setOcrOrigin(jsonObject.toString(2));
        return invoiceStruct;
    }
}
